<template>
  <div>
    <div class="file-list">
      <el-scrollbar class="scorll-Y" :style="{
          height: fileList.length > 2 ? '50px' : fileList.length * 30 + 'px',
        }">
        <div class="file-item" v-for="(item, index) in fileList" :key="index">
          <div>
            <i class="el-icon-link"></i>
            <el-tooltip popper-class="hc-dec-text" v-if="item.fileName.length > filenameLength" :content="item.fileName" placement="top" effect="light">
              <span class="filename" type="link" @click="openWithWps(item)">{{
                item.fileName.substring(0, filenameLength) + "..."
              }}</span>
            </el-tooltip>
            <span v-else class="filename" type="link" :title="item.fileName" @click="openWithWps(item)">{{ item.fileName }}</span>
          </div>
          <div>
            <span class="btn-down" @click="handleDownload(item)">下载</span>
            <span class="btn-remove" v-if="!disabled" @click="deleteFile(item)">删除</span>
          </div>
        </div>
      </el-scrollbar>
    </div>

    <el-upload v-if="!disabled" ref="upload" class="avatar-uploader" action="false" :http-request="uploadFile" :show-file-list="false" :before-upload="beforeAvatarUpload" multiple :limit="localLimit" :on-exceed="handleExceed" :onChange="changeFile">
      <el-button size="mini" type="primary">点击上传({{fileList.length}}/{{localLimit}})</el-button>
    </el-upload>
  </div>
</template>

<script>
import
{
  openUpload,
  getOpenDownloadFile,
  getOpenDownloadUrl,
  delAttachment,
  getOpenList,
} from "../api/common/attachment";
import request from '@/utils/request'
import filePreview from "../utils/filePreview";
export default {
  name: "imgUpdata",
  props: {
    relationUnid: {
      type: [String, Number],
    },
    moduleName: {
      type: String,
    },
    limit: {
      type: Number,
      default: 10,
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    ctrlProps: {
        type: Object,
        required: false,
    },
  },
  data()
  {
    return {
      file: null,
      imgUrl: this.value,
      fileList: [],
      filenameLength: window.HC_config.VUE_SHOW_FILENAME_LENGTH || 6,
      localLimit: this.limit,
    };
  },
  created()
  {
    if (this.relationUnid)
    {
      this.getOpenList();
    }
  },
  mounted()
  {
    if (this.ctrlProps)
    {
      this.localLimit = this.ctrlProps.limit || 10;
    }
  },
  methods: {
    getOpenDownloadFile,
    getOpenList()
    {
      getOpenList({
        relationUnid: this.relationUnid,
        moduleName: this.moduleName,
        pageNum: 1,
        pageSize: 100,
      })
        .then((res) =>
        {
          if (res.result)
          {
            this.fileList = res.result.data || [];
          } else
          {
            this.fileList = [];
          }
        })
        .catch((err) =>
        {
          console.log(err);
        });
    },
    /**
     * 删除文件
     */
    deleteFile(item)
    {
      this.$confirm("此操作将永久删除, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() =>
        {
          delAttachment({ unids: item.unid })
            .then((res) =>
            {
              if (res.code === 200)
              {
                this.$message.success("附件删除成功");
                this.getOpenList();
                  // 手动上传需要移除
                  this.$refs.upload.handleRemove(this.file);
              } else
              {
                this.$message.error(res.message);
              }
            })
            .catch((err) =>
            {
              console.log(err);
            });
        })
        .catch(() => { });
    },
    // openWithWps(file)
    // {
    //   console.log(getOpenDownloadFile(file.filePath));
    //   // return
    //   if (file.fileName.indexOf(".pdf") != -1)
    //   {
    //     window.open("/showpdf?type=attachment&filePath=" + file.filePath);
    //   } else
    //   {
    //     this.$message.warning("该文件不支持在线预留,请下载后打开");
    //   }
    // },
    //在线预览文件
    openWithWps(file)
    {
      filePreview(file);
    },
       //文件下载
    handleDownload(file)
    {
      // window.open(getOpenDownloadUrl(file.unid));

      let requestParams = {
        url: getOpenDownloadUrl(file.unid),
        method: "get",
        responseType: 'blob'
      };

      let fileName = file.fileName;
      //执行请求
      request(requestParams)
        .then((res) =>
        {
          if (res instanceof Blob)
          {
            this.download(res, fileName);
          }
          else if (res.data instanceof Blob)
          {
            this.download(res.data, fileName);
          }
        })
    },
    download(data, fileName)
    {
      if (!data)
      {
        return;
      }
      let url = window.URL.createObjectURL(new Blob([data]));
      let link = document.createElement("a");
      link.style.display = "none";
      link.href = url;
      link.setAttribute("download", fileName);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    /**
     * 2022-4-21 chenshuai
     * 自定义上传
     */
    uploadFile()
    {
      const formData = new FormData();
      formData.append("file", this.file.raw);
      formData.append("relationUnid", this.relationUnid);
      formData.append("moduleName", this.moduleName);
      formData.append("type", 1);
      openUpload(formData, (progress) =>
      {
        console.log(progress);
      }).then((res) =>
      {
        this.getOpenList();
        this.$emit("getFile", this.file.raw);
        this.$emit("uploadFile", res.result);
      });
    },
    /**
     * 上传校验
     */
    beforeAvatarUpload(file)
    {
      console.log("==============cs")
      if (this.fileList.length >= this.localLimit)
      {
          this.$message.error(`最多上传${this.localLimit}个文件`);
          return false;
      }
      const isLt2M = file.size / 1024 / 1024 < 100;

      if (!isLt2M)
      {
        this.$message.error("上传文件大小不能超过 100MB!");
      }
      return isLt2M;
    },
    handleExceed(files, fileList)
    {
      console.log("==============cs")
      if (this.fileList.length >= this.localLimit)
      {
          this.$message.error(`最多上传${this.localLimit}个文件`);
      }
    },
    changeFile(file, fileList)
    {
      this.file = file;
      console.log(file);
    },
  },
};
</script>

<style lang="scss" scoped>
.file-list {
  display: flex;
  flex-direction: column;
  width: 200px;
  .file-item {
    width: 100%;
    justify-content: space-between;
    align-items: center;
    display: flex;
    font-size: 14px;
    color: #409eff;
    margin-top: 5px;
    .el-icon-link {
      font-size: 18px;
      margin-right: 5px;
      transform: translateY(2px);
    }
    .btn-down {
      color: #409eff;
      cursor: pointer;
    }
    .btn-remove {
      color: #f56c6c;
      cursor: pointer;
      margin-left: 10px;
    }
  }
}

::v-deep .el-scrollbar__wrap {
  overflow-x: hidden;
}
</style>
